<template>
  <div class="chat-container">
    <!-- 聊天记录区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(msg, index) in messages" :key="index" class="message-wrapper">
        <!-- AI消息 -->
        <div v-if="!msg.isUser"
             class="message ai-message"
             :class="[msg.type]">
          <div class="avatar ai-avatar">
            <AiAvatarFallback :type="aiType" />
          </div>
          <div class="message-bubble">
            <!-- 思考过程 -->
            <div v-if="msg.thoughtProcess" class="thought-process">
              <div class="thought-header">
                <span class="thought-icon">💭</span>
                <span class="thought-title">思考过程</span>
              </div>
              <div class="thought-content"
     v-html="formatThoughtProcess(msg.thoughtProcess)"
     :class="{ 'streaming': msg.isStreaming }">
</div>
            </div>
            <!-- 主要内容（如果没有思考过程，则显示主要内容） -->
            <div v-if="!msg.thoughtProcess" class="message-content">
              {{ msg.content }}
              <span v-if="connectionStatus === 'connecting' && index === messages.length - 1" class="typing-indicator">▋</span>
            </div>
            <div class="message-time">{{ formatTime(msg.time) }}</div>
          </div>
        </div>
        
        <!-- 用户消息 -->
        <div v-else class="message user-message" :class="[msg.type]">
          <div class="message-bubble">
            <div class="message-content">{{ msg.content }}</div>
            <div class="message-time">{{ formatTime(msg.time) }}</div>
          </div>
          <div class="avatar user-avatar">
            <div class="avatar-placeholder">我</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-container">
      <div class="chat-input">
        <textarea 
          v-model="inputMessage" 
          @keydown.enter.prevent="sendMessage"
          placeholder="请输入消息..." 
          class="input-box"
          :disabled="connectionStatus === 'connecting'"
        ></textarea>
        <button 
          @click="sendMessage" 
          class="send-button"
          :disabled="connectionStatus === 'connecting' || !inputMessage.trim()"
        >发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue'
import AiAvatarFallback from './AiAvatarFallback.vue'

const props = defineProps({
  messages: {
    type: Array,
    default: () => []
  },
  connectionStatus: {
    type: String,
    default: 'disconnected'
  },
  aiType: {
    type: String,
    default: 'default'  // 'love' 或 'super'
  }
})

const emit = defineEmits(['send-message'])

const inputMessage = ref('')
const messagesContainer = ref(null)

// 根据AI类型选择不同头像
const aiAvatar = computed(() => {
  return props.aiType === 'love' 
    ? '/ai-love-avatar.png'  // 恋爱大师头像
    : '/ai-super-avatar.png' // 超级智能体头像
})

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) return
  
  emit('send-message', inputMessage.value)
  inputMessage.value = ''
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 格式化思考过程
const formatThoughtProcess = (thoughtProcess) => {
  if (!thoughtProcess) return ''

  // 处理AI的真实思考内容，保持流式输出的自然感
  let formatted = thoughtProcess
    .replace(/\n\n/g, '</div><div class="thought-block">') // 双换行分隔思考块
    .replace(/\n/g, '<br>') // 单换行转为换行
    .replace(/Step (\d+):/g, '<strong>步骤 $1：</strong>') // 步骤标识
    .replace(/([。！？])\s*/g, '$1</div><div class="thought-block">') // 句子分隔
    .replace(/💡\s*\*\*(.+?)\*\*/g, '<div class="completion-notice info"><span class="completion-icon">💡</span><span class="completion-title">$1</span></div>') // 任务完成提示（信息类）
    .replace(/✅\s*\*\*(.+?)\*\*/g, '<div class="completion-notice success"><span class="completion-icon">✅</span><span class="completion-title">$1</span></div>') // 任务完成提示（成功类）
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>') // 粗体文本

  // 确保最后一段也有thought-block包装
  if (!formatted.endsWith('</div>')) {
    formatted = '<div class="thought-block">' + formatted + '</div>'
  }

  return formatted
}

// 自动滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 监听消息变化与内容变化，自动滚动
watch(() => props.messages.length, () => {
  scrollToBottom()
})

watch(() => props.messages.map(m => m.content).join(''), () => {
  scrollToBottom()
})

onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 70vh;
  min-height: 600px;
  background-color: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  padding-bottom: 80px; /* 为输入框留出空间 */
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 72px; /* 与输入框高度相匹配 */
}

.message-wrapper {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.message {
  display: flex;
  align-items: flex-start;
  max-width: 85%;
  margin-bottom: 8px;
}

.user-message {
  margin-left: auto; /* 用户消息靠右 */
  flex-direction: row; /* 正常顺序，先气泡后头像 */
}

.ai-message {
  margin-right: auto; /* AI消息靠左 */
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar {
  margin-left: 8px; /* 用户头像在右侧，左边距 */
}

.ai-avatar {
  margin-right: 8px; /* AI头像在左侧，右边距 */
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #007bff;
  color: white;
  font-weight: bold;
}

.message-bubble {
  padding: 0;
  border-radius: 0;
  position: relative;
  word-wrap: break-word;
  min-width: 120px;
  background: transparent;
  box-shadow: none;
}

.user-message .message-bubble {
  text-align: left;
}

.ai-message .message-bubble {
  text-align: left;
}

.message-content {
  font-size: 15px;
  line-height: 1.6;
  white-space: pre-wrap;
  padding: 16px 20px;
  border-radius: 16px;
  position: relative;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

/* 用户消息内容样式 */
.user-message .message-content {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  box-shadow:
    0 4px 12px -2px rgba(59, 130, 246, 0.3),
    0 2px 8px -1px rgba(59, 130, 246, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.user-message .message-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
}

/* AI消息内容样式 */
.ai-message .message-content {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  color: #374151;
  box-shadow:
    0 4px 12px -2px rgba(0, 0, 0, 0.1),
    0 2px 8px -1px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.ai-message .message-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.1), transparent);
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 4px;
  text-align: right;
}

.chat-input-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1px solid #e0e0e0;
  z-index: 100;
  height: 72px; /* 固定高度 */
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.chat-input {
  display: flex;
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
  align-items: center;
}

.input-box {
  flex-grow: 1;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 10px 16px;
  font-size: 16px;
  resize: none;
  min-height: 20px;
  max-height: 40px; /* 限制高度 */
  outline: none;
  transition: border-color 0.3s;
  overflow-y: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE & Edge */
}

/* 隐藏Webkit浏览器的滚动条 */
.input-box::-webkit-scrollbar {
  display: none;
}

.input-box:focus {
  border-color: #007bff;
}

.send-button {
  margin-left: 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 0 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  height: 40px;
  align-self: center;
}

.send-button:hover:not(:disabled) {
  background-color: #0069d9;
}

.typing-indicator {
  display: inline-block;
  animation: blink 0.7s infinite;
  margin-left: 2px;
}

@keyframes blink {
  0% { opacity: 0; }
  50% { opacity: 1; }
  100% { opacity: 0; }
}

.input-box:disabled, .send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message {
    max-width: 95%;
  }
  
  .message-content {
    font-size: 15px;
  }
  
  .chat-input {
    padding: 12px;
  }
  
  .input-box {
    padding: 8px 12px;
  }
  
  .send-button {
    padding: 0 15px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .avatar {
    width: 32px;
    height: 32px;
  }
  
  .message-bubble {
    padding: 10px;
  }
  
  .message-content {
    font-size: 14px;
  }
  
  .chat-input-container {
    height: 64px;
  }
  
  .chat-messages {
    bottom: 64px;
  }
}

/* 新增：不同类型消息的样式 */
.ai-answer {
  animation: fadeIn 0.3s ease-in-out;
}

.ai-final {
  /* 最终回答，可以有不同的样式，例如边框高亮等 */
}

.ai-error {
  opacity: 0.7;
}

.user-question {
  /* 用户提问的特殊样式 */
}

/* 连续消息气泡样式 */
.ai-message + .ai-message {
  margin-top: 4px;
}

.ai-message + .ai-message .avatar {
  visibility: hidden;
}

.ai-message + .ai-message .message-bubble {
  border-top-left-radius: 10px;
}

/* 思考过程样式 */
.thought-process {
  margin-bottom: 16px;
  padding: 0;
  background: transparent;
  border-radius: 0;
  border: none;
}

.thought-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 13px;
  font-weight: 600;
  color: #8b5cf6;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.thought-icon {
  margin-right: 8px;
  font-size: 18px;
  filter: drop-shadow(0 1px 2px rgba(139, 92, 246, 0.3));
  animation: pulse 2s infinite;
}

.thought-title {
  font-weight: 600;
  background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.thought-content {
  font-size: 14px;
  line-height: 1.6;
  color: #374151;
  background: linear-gradient(135deg, #fefefe 0%, #f8fafc 100%);
  padding: 16px 20px;
  border-radius: 16px;
  border: 1px solid rgba(139, 92, 246, 0.1);
  box-shadow:
    0 4px 6px -1px rgba(139, 92, 246, 0.1),
    0 2px 4px -1px rgba(139, 92, 246, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  position: relative;
  overflow: hidden;
}

/* 流式输出的打字机效果 */
.thought-content {
  position: relative;
}

.thought-content::after {
  content: '';
  position: absolute;
  right: 16px;
  bottom: 16px;
  width: 8px;
  height: 20px;
  background: linear-gradient(135deg, #8b5cf6, #a855f7);
  border-radius: 4px;
  animation: typingCursor 1s infinite;
  visibility: hidden;
  opacity: 0;
}

.thought-content.streaming::after {
  visibility: visible;
  opacity: 1;
}

@keyframes typingCursor {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

.thought-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.4), transparent);
}

.thought-block {
  margin-bottom: 8px;
  padding: 0;
  position: relative;
}

.thought-block:last-child {
  margin-bottom: 0;
}

.thought-block::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(139, 92, 246, 0.1), transparent);
}

/* 流式输出的动画效果 */
.thought-content {
  animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(15px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.05);
  }
}

@keyframes shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
}

/* 消息气泡悬停效果 */
.message-content:hover,
.thought-content:hover {
  transform: translateY(-1px);
  box-shadow:
    0 8px 16px -2px rgba(0, 0, 0, 0.15),
    0 4px 12px -1px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

/* 用户消息悬停效果 */
.user-message .message-content:hover {
  box-shadow:
    0 8px 16px -2px rgba(59, 130, 246, 0.4),
    0 4px 12px -1px rgba(59, 130, 246, 0.3);
}

/* AI消息悬停效果 */
.ai-message .message-content:hover,
.thought-content:hover {
  box-shadow:
    0 8px 16px -2px rgba(0, 0, 0, 0.15),
    0 4px 12px -1px rgba(0, 0, 0, 0.1);
}

/* 打字指示器优化 */
.typing-indicator {
  display: inline-block;
  animation: typingPulse 1.2s infinite;
  margin-left: 2px;
  font-weight: bold;
}

@keyframes typingPulse {
  0%, 100% {
    opacity: 0.3;
  }
  50% {
    opacity: 1;
  }
}

/* 消息时间戳优化 */
.message-time {
  font-size: 11px;
  opacity: 0.6;
  margin-top: 6px;
  text-align: right;
  font-weight: 500;
  letter-spacing: 0.3px;
}

/* 任务完成提示样式 */
.completion-notice {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 20px;
  margin: 12px 0;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  position: relative;
  overflow: hidden;
  animation: slideInRight 0.5s ease-out;
}

.completion-notice.info {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  color: #92400e;
  border: 1px solid rgba(245, 158, 11, 0.2);
  box-shadow:
    0 4px 12px -2px rgba(245, 158, 11, 0.2),
    0 2px 8px -1px rgba(245, 158, 11, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
}

.completion-notice.success {
  background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
  color: #065f46;
  border: 1px solid rgba(34, 197, 94, 0.2);
  box-shadow:
    0 4px 12px -2px rgba(34, 197, 94, 0.2),
    0 2px 8px -1px rgba(34, 197, 94, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
}

.completion-notice::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5), transparent);
}

.completion-icon {
  font-size: 20px;
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
  animation: bounce 2s infinite;
}

.completion-title {
  font-weight: 600;
  font-size: 15px;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}
</style> 